package com.moyun.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.Serializable;
import java.net.URI;
import java.util.Map;

/**
 * <h3>moyun-base</h3>
 * <p>RestTemplate的工具类</p>
 *
 * @author : ybx
 * @date : 2021-07-09 17:39:33
 **/
@Component
public class RestTemplateUtil implements Serializable {

    /**
     * 实际执行请求的template
     */
    @Autowired
    private RestTemplate restTemplate;


    /**
     * get 请求
     *
     * @param url
     * @param params
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T get(String url, LinkedMultiValueMap<String, String> params, Map<String, String> headersMap, Class<T> cls) {

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.queryParams(params).build().toUri();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (!CollectionUtils.isEmpty(headersMap)) {
            for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                headers.set(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<Object> request = new HttpEntity<>(headers);

        ResponseEntity<T> exchange = this.restTemplate.exchange(uri, HttpMethod.GET, request, cls);
        T body = exchange.getBody();

        return body;

    }

    /**
     * json请求
     *
     * @param url
     * @param entity
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T post(String url, Object entity, Class<T> cls) {
        HttpEntity<Object> request = new HttpEntity<>(entity);
        return executePost(url, request, cls);
    }

    /**
     * 表单请求
     *
     * @param url
     * @param params
     * @param cls
     * @param <T>
     * @return
     */
    public <T> T formPost(String url, MultiValueMap<String, Object> params, Class<T> cls) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<Object> request = new HttpEntity<>(params, headers);
        return executePost(url, request, cls);
    }

    /**
     * post 请求
     *
     * @param url
     * @param request
     * @param cls
     * @param <T>
     * @return
     */
    private <T> T executePost(String url, HttpEntity<Object> request, Class<T> cls) {
        ResponseEntity<T> exchange = this.restTemplate.exchange(url, HttpMethod.POST, request, cls);
        return exchange.getBody();
    }


}